#!/bin/bash

LOG_FILE="/home/shr/MyGitee/personal-study/20241218_cron_t/logfile.log"
URL="https://www.sohu.com/"
RETRY_COUNT=3
RETRY_INTERVAL=30

# 获取当前时间
current_hour=$(date +%H)

# 检查是否在3:00到5:00之间
if [ "$current_hour" -ge 03 ] && [ "$current_hour" -lt 05 ]; then
    sleep $((RANDOM % 3600))  # 随机延迟0到1小时以错峰请求

    # 尝试访问并记录结果
    for try in $(seq 1 $RETRY_COUNT); do
        response=$(curl -s -w "%{http_code}\n" "$URL")

        if [ "$response" -eq 200 ]; then
            echo "$(date '+%Y-%m-%d %H:%M:%S') - OK" >> "$LOG_FILE"
            exit 0
        else
            echo "$(date '+%Y-%m-%d %H:%M:%S') - try $try: FAIL (HTTP code $response)" >> "$LOG_FILE"
            if [ "$try" -ne "$RETRY_COUNT" ]; then
                sleep "$RETRY_INTERVAL"
            fi
        fi
    done

    # 三次尝试都失败，记录最终失败
    echo "$(date '+%Y-%m-%d %H:%M:%S') - End: FAIL after $RETRY_COUNT attempts" >> "$LOG_FILE"
fi
